% File which calculates the threshold "indifference" value of risk aversion
% for each binary lottery in the experiment

load lottery_task_info

% CRRA utility does not easily work with lotteries giving 0 payoff. CRRA2
% stays positive for payments>$1
lotteries(45,4)=.01;
if CRRA2==1
    lotteries(45,4)=1.01;
end

options = optimoptions('fsolve','Display','iter','TolFun',1e-20,'MaxFunEvals', 10000);
iter_n=30;
omega_th_final1=zeros(55,1);
for i=1:55
    omega_th1=10;
    omega_table=zeros(iter_n,1);
    fval_table=ones(iter_n,1)*10;
    % lottery one is the safer one
    a1=lotteries(i,1);
    b1=lotteries(i,2);
    p_a1=lotteries(i,3);
    % lottery 2 is the riskier one
    a2=lotteries(i,4);
    b2=lotteries(i,5);
    p_a2=lotteries(i,6);

    

    iter=0;
    while iter<iter_n 
            iter

            try
                rng('shuffle')
                %%% for CARA
                if CARA==1
                    theta1=randn(1,1)/20;
                    [omega_th1, fval]=fsolve(@threshold_function_ep,theta1, options)  
                %%% for Expo-Power
                elseif ep==1
                    theta1=randn(1,1);
                    [omega_th1, fval]=fsolve(@threshold_function_CARA,theta1, options)    
                %%% for CRRA
                else
                    theta1=randn(1,1);
                    [omega_th1, fval]=fsolve(@threshold_function,theta1, options)  
                end

                            
           catch ME

                    continue;
            end
            iter=iter+1
            i

            fval_table(iter)=fval;
            omega_table(iter)=omega_th1;
    end

    [min_val,position]=min(abs(fval_table));
    omega_th_final1(i)=omega_table(position);
    i
end

% set indifference thresholds to infinity for dominated options
omega_th_final1([10 20 30])=Inf;
